package com.java.javassist.helloworld;

import javassist.*;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Description: javassit 生成helloworld类,入门
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/10/21-09:35
 */
public class HelloWorldTest {

    public static void main(String[] args) throws NotFoundException, CannotCompileException, IOException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //回去class池
        ClassPool classPool = ClassPool.getDefault();
        //创建class
        CtClass ctClass = classPool.makeClass("com.yexx.javassit.Helloworld");

        //创建方法,指定返回类型为void, 方法名称为 main 参数列表类型为 String[]
        CtMethod ctMethod = new CtMethod(CtClass.voidType, "main", new CtClass[]{classPool.get(String[].class.getName())}, ctClass);
        //添加方法的修饰(public static)
        ctMethod.setModifiers(Modifier.PUBLIC + Modifier.STATIC);
        //添加方法内代码块
        ctMethod.setBody("{System.out.println(\"hello this is javassit world,make happy\");}");
        //给class添加方法
        ctClass.addMethod(ctMethod);

        //创建无参数构造函数
        CtClass[] parameters;
        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, ctClass);
        //添加构造函数代码块
        ctConstructor.setBody("{System.out.println(\"init constructor...\");}");
        //给class设置构造函数
        ctClass.addConstructor(ctConstructor);

        //写入磁盘文件:相当于创建class
        ctClass.writeFile();

        //实例化
        Class aClass = ctClass.toClass();
        Object aObj = aClass.getDeclaredConstructor().newInstance();

        //获取方法
        Method mainMethod = aClass.getDeclaredMethod("main", String[].class);

        //反射执行
        mainMethod.invoke(aObj, (Object) new String[]{});

    }
}
